package com.example.common.Interceptor;

import com.example.common.Utils.JwtUtil;
import com.example.common.web.exception.CustomerException;
import com.example.common.web.response.ResultCode;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/11/2-11-02-10:53
 * @Description：com.example.cms.web.Interceptor   Jwt拦截器
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //认证资源才需要走该过滤器 （跨域的options放行）  TODO
            //
        if(!(handler instanceof HandlerMethod)){
            //不需要拦截的资源
            return true;
        }
        //获取请求头中的token
        String token = request.getParameter("Authorization");
        //如果为空，， 未登录
        System.out.println(token);
        if(!StringUtils.hasText(token)){
            throw new CustomerException(ResultCode.USER_NOT_LOGIN);
        }
        //token过期 token篡改 token是否合法
        JwtUtil.checkSign(token);
        //取出token的信息 业务操作
        Map<String, Object> info = JwtUtil.getInfo(token);
        info.forEach((k,v)-> System.out.println(k+" = " + v));
        return true;
    }
}
